/*2S7LXljdWdGhrCxZ1MFl4nbo76lbmNV/zj9vAsZ4TsJjt35I/W4VBwuu/33I9fcb*/
/*
 * @Author: xiahui
 * @PageInfo: 采购合同维护卡片态
 * @Date: 2019-01-10 17:35:16
 * @Last Modified by: heyfn
 * @Last Modified time: 2022-07-25 17:10:43
 */
import React, { Component } from 'react';
import { createPage, base, high , ajax} from 'nc-lightapp-front';
import { initTemplate } from './init';
import {
	AREA,
	URL,
	PAGECODE,
    APPCODE,
	BUTTONID,
	DATASOURCECACHE,
	UISTATUS,
	FIELDS,
	CARDTABLEAREAIDS,
	CARDTABLEAREANAMES
} from '../constance';
import { buttonClick, lineBtnClick, pageInfoClick } from './btnClicks';
import saveAndCommit from './btnClicks/saveAndCommit';
import { headAfterEvent, bodyAfterEvent } from './afterEvents';
import { headBeforeEvent, bodyBeforeEvent } from './beforeEvents';
import { onRowsSelected } from './viewControl/buttonControl';
import { buttonControl } from './viewControl/buttonControl';
import { RownoUtils } from '../../../../scmpub/scmpub/pub/tool/cardTableTools';
import { getAreaAndBtnId } from '../utils/cardPageUtil';
import ControlScopeDlg from '../../pub/components/ControlScopeDlg';
import DocManagement from '../../pub/components/DocManagement';
import { getCardDisableHotKeyBtn } from '../../../../scmpub/scmpub/pub/tool/hotKeysUtil';
import MulTabPane from 'scmpub/scmpub/components/MulTabPane';
import commitBtnClick from './btnClicks/commitBtnClick';
import ApprovalTrans from 'uap/common/components/approvalTrans';
import inputChange from '../../../../scmpub/scmpub/pub/tool/rownoInputUtil';
import { initLang, getLangByResId } from '../../../../scmpub/scmpub/pub/tool/multiLangUtil';
import { createCardTitle } from '../../../../scmpub/scmpub/pub/tool/titleUtil';
import ApproveDetail from 'uap/common/components/ApproveDetail';
import NCUploader from 'uap/common/components/NCUploader';
import { batchEvents } from './batchEvents';
import { TempDataList } from 'scmpub/scmpub/components/TempSave';
import temporaryClick from './btnClicks/temporaryClick';

// 分摊明细-引入自定义页签meta
import tablemeta from './custom.json';

const { BillTrack } = high;
const { NCAffix, NCDiv, NCAnchor, NCScrollElement, NCScrollLink } = base;

class PurdailyCard extends Component {
	constructor(props) {
		super(props);

		props.use.cardTable(
			AREA.cardTableId,
			AREA.cardTermId,
			AREA.cardPayId,
			AREA.cardFeeId,
			AREA.cardMemoraId,
			AREA.cardChangeId,
			AREA.cardExecutId
		);
		props.use.form(AREA.cardFormId);

        // 分摊明细-注册不可编辑表格
        props.use.cardTable('list_head');

		this.state = {
			pk: '',
			billtype: '',
			showTrack: false,
			showApproveInfo: false,
			showUploader: false,
			showControl: false, // 合同范围控制
			showPane: false, // 变更历史
			isBatchControl: false, // 是否批量控制
			target: null,
			showDoc: false, //半结构化文档管理弹窗
			compositedisplay: false, // 提交指派组件显示隐藏
			compositedata: null, // 提交指派组件数据
			saveAndCommit: false, //是否保存提交
			tempDataList: [], // 暂存数据
			showTemp: false
		};
		(this.copyRowDatas = null), // 复制行数据
			this.contexts; // 发布交易类型处理
		this.approveFlag = false; // 是否审批中心页面进入
		this.bodyActionFlag = true; //操作列按钮可用标志
		this.reason = null; // 脚本操作原因
		// 所有复制行数据
		this.copyLineDatas = {
			[AREA.cardTableId]: null,
			[AREA.cardTermId]: null,
			[AREA.cardPayId]: null,
			[AREA.cardFeeId]: null,
			[AREA.cardMemoraId]: null
		};
		this.skipCodes = []; //交互式异常码
		initLang(this, [ '4004purdaily' ], 'ct', initTemplate.bind(this, this.props));
	}

	componentWillMount() {
		// 关闭浏览器
		window.onbeforeunload = () => {
			let status = this.props.cardTable.getStatus(AREA.cardTableId);
			if (status == UISTATUS.edit) {
				return getLangByResId(this, '4004PURDAILY-000046'); /* 国际化处理： 当前单据未保存，您确认离开此页面*/
			}
		};
		this.approveFlag = this.props.getUrlParam('scene') === 'approvesce';

        // 分摊明细-导入meta
        this.props.meta.addMeta(tablemeta)
	}

	// 获取列表肩部信息
	getTableHead = (moduleId) => {
		let { bodyAreaId } = getAreaAndBtnId(moduleId); // 肩部按钮区域
		if (bodyAreaId) {
			return (
				<div className="shoulder-definition-area">
					<div className="definition-icons">
						{this.props.button.createButtonApp({
							area: bodyAreaId,
							ignoreHotkeyCode: getCardDisableHotKeyBtn(),
							onButtonClick: lineBtnClick.bind(this, moduleId)
						})}
					</div>
				</div>
			);
		}
	};

	// 楼层点击回调函数
	clickFunction = (moduleId) => {
		this.props.cardTable.toggleCardTable(moduleId, true);
	};

	// 脚本操作对话框回调
	changeReason = (reason) => {
		this.reason = reason;
	};

	toggleDocShow = () => {
		this.setState({
			showDoc: !this.state.showDoc
		});
	};

	// 提交指派获取结果后重新进行提交
	getResult = (value) => {
		//重新执行提交操作重新执行提交操作
		if (this.state.saveAndCommit == true) {
			saveAndCommit.call(this, this.skipCodes, value);
		} else {
			commitBtnClick.call(this, this.props, null, null, value);
		}
		this.setState({ compositedisplay: false, saveAndCommit: false });
	};

	/**
     * 暂存
     */
	creatTempDataList = () => {
		return this.state.showTemp ? (
			<TempDataList
				parentProps={this.props}
				display={this.state.showTemp}
				config={{
					pagecode: PAGECODE.cardPagecode,
					type: 'card',
					processorstr: 'nccloud.web.ct.purdaily.action.PurdailyTempSaveProcessor' //精度处理
				}}
				addTemporary={this.state.tempDataList}
				close={() => {
					this.setState({ showTemp: false });
				}}
				clickTemporary={temporaryClick.bind(this)}
			/>
		) : (
			''
		);
	};

    
    componentDidMount() {
        let billid = this.props.getUrlParam('id');
        if(billid){
            //分摊明细请求
            ajax({
                url:'/nccloud/ct/purdaily/queryShare.do',
                data:{
                    pk_ct_pu:billid,
                    pagecode: PAGECODE.cardPagecode,
                    appcode:APPCODE.appcodez2
                },
                success: (res) => {
                    console.log(res,"resssss")
                    if (res.success && res.data) {
                        if(res.data['body'].rows.length>0){
                            //处理分摊明细数据
                            this.props.cardTable.setTableData('list_head', res.data['body']);
                        }else{
                            //  清空分摊明细数据
                            this.props.cardTable.setTableData('list_head',{rows:[]});
                        }
                        
                    }
                }
            });
        }
    }

	render() {
		const { button, BillHeadInfo, cardTable, form, cardPagination, transferTable, modal } = this.props;
		const { createCardPagination } = cardPagination;
		let { createForm } = form;
		let { createCardTable } = cardTable;
		const { createBillHeadInfo } = BillHeadInfo;
		const { createTransferList } = transferTable;
		const { createModal } = modal;
		const { socket } = this.props;

		let source = this.props.getUrlParam('source');
		let pk = this.props.form.getFormItemsValue(AREA.cardFormId, FIELDS.pk_ct_pu).value; // 主键

		let ref = source == URL.ref20 || source == URL.ref28; // 来源于转单（请购单、价格审批单）
		let channelType = this.props.getUrlParam('channelType'); //推单标识
		if (channelType && channelType == 'priceaudit') {
			ref = channelType;
		}
		if (ref) {
			return (
				<div id="transferCard" className="nc-bill-transferList">
					{createConnectMesg(socket)}
					<NCAffix>
						<NCDiv areaCode={NCDiv.config.HEADER} className="nc-bill-header-area">
							{headerTitleArea.call(this, createBillHeadInfo)}
							{headerButtonArea.call(this, button)}
						</NCDiv>
					</NCAffix>
					<div className="nc-bill-transferList-content">
						{transferListArea.call(this, createTransferList)}
						<div className="transferList-content-right nc-bill-extCard" id="puarrival-card">
							{floorArea.call(this)}
							{billFromArea.call(this, createForm)}
							<div className="nc-bill-bottom-area">{billTableArea.call(this, createCardTable)}</div>
						</div>
					</div>
					{billPublicArea.call(this, createModal, pk)}
					{createModal('code-config')}
					{createModal('printService', {
						className: 'print-service'
					})}
					<iframe id="printServiceframe" name="printServiceframe" style={{ display: 'none' }} />
				</div>
			);
		} else {
			return (
				<div className="nc-bill-extCard" id="scm-ct-purdaily-card">
					{createConnectMesg(socket)}
					<div className="nc-bill-top-area">
						<NCAffix>
							<NCDiv areaCode={NCDiv.config.HEADER} className="nc-bill-header-area">
								{headerTitleArea.call(this, createBillHeadInfo)}
								{headerButtonArea.call(this, button)}
								{!this.approveFlag ? headerCardPaginationArea.call(this, createCardPagination) : ''}
							</NCDiv>
						</NCAffix>
						{floorArea.call(this)}
						{billFromArea.call(this, createForm)}
					</div>
					<div className="nc-bill-bottom-area">{billTableArea.call(this, createCardTable)}</div>
					{billPublicArea.call(this, createModal, pk)}
					{/* 暂存数据 */}
					{this.creatTempDataList()}
					{createModal('code-config')}
					{createModal('printService', {
						className: 'print-service'
					})}
					<iframe id="printServiceframe" name="printServiceframe" style={{ display: 'none' }} />
				</div>
			);
		}
	}
}

//socket区
function createConnectMesg(socket) {
	return (
		<div>
			{socket.connectMesg({
				headBtnAreaCode: AREA.card_head, // 表头按钮区域ID
				formAreaCode: AREA.cardFormId, // 表头Form区域ID
				billtype: 'Z2',
				billpkname: FIELDS.pk_ct_pu,
				dataSource: DATASOURCECACHE.dataSourceListCacheKey
			})}
		</div>
	);
}

// 标题区
function headerTitleArea(createBillHeadInfo) {
	return (
		<div className="header-title-search-area">
			{createCardTitle(this, {
				billCode: '', //单据号
				backBtnClick: buttonClick.bind(this, this.props, BUTTONID.Back)
			}) /* 国际化处理： 采购合同维护*/}
		</div>
	);
}

// 按钮区
function headerButtonArea(button) {
	return (
		<div className="header-button-area">
			{button.createErrorFlag({
				headBtnAreaCode: AREA.card_head
			})}
			{button.createButtonApp({
				area: AREA.card_head,
				onButtonClick: buttonClick.bind(this)
			})}
		</div>
	);
}

// 翻页区
function headerCardPaginationArea(createCardPagination) {
	return (
		<div className="header-cardPagination-area">
			{createCardPagination({
				dataSource: DATASOURCECACHE.dataSourceListCacheKey,
				handlePageInfoChange: pageInfoClick.bind(this)
			})}
		</div>
	);
}

// 转单区
function transferListArea(createTransferList) {
	return createTransferList({
		//表格组件id
		headcode: AREA.cardFormId,
		bodycode: CARDTABLEAREAIDS,
		transferListId: AREA.cardLeftId,
		dataSource: DATASOURCECACHE.dataSourceRef20CacheKey,
		pkname: FIELDS.pk_praybill,
		onTransferItemSelected: (record, status, index) => {
			ref20Selected.call(this, status, index, record);
		},
		onTransferItemClick: (record, index, status) => {
			ref20Selected.call(this, status, index, record);
		}
	});
}

// 楼层区
function floorArea() {
	return (
		<div className="nc-bill-table-area">
			<NCAnchor>
				<NCScrollLink to={AREA.cardFormId} spy={true} smooth={true} duration={300} offset={-100}>
					<p>{getLangByResId(this, '4004PURDAILY-000048')}</p>
					{/* 国际化处理： 基本信息*/}
				</NCScrollLink>
				{CARDTABLEAREAIDS.map((moduleId, index) => {
					return (
						<NCScrollLink
							to={moduleId}
							spy={true}
							smooth={true}
							duration={300}
							offset={-100}
							clickFun={this.clickFunction.bind(this, moduleId)}
						>
							<p>{getLangByResId(this, CARDTABLEAREANAMES[index])}</p>
						</NCScrollLink>
					);
				})}
			</NCAnchor>
		</div>
	);
}

// 表单区
function billFromArea(createForm) {
	return (
		<div className="nc-bill-form-area">
			<NCScrollElement name={AREA.cardFormId}>
				{createForm(AREA.cardFormId, {
					onBeforeEvent: headBeforeEvent.bind(this),
					onAfterEvent: headAfterEvent.bind(this)
				})}
			</NCScrollElement>
		</div>
	);
}

// 表格区
function billTableArea(createCardTable) {
	return (
		<div className="nc-bill-tableTab-area">
			{CARDTABLEAREAIDS.map((moduleId) => {
				return (
					<NCScrollElement name={moduleId}>
						{createCardTable(moduleId, {
							tableHead: this.getTableHead.bind(this, moduleId),
							hideAdd: moduleId == AREA.cardTableId ? false : true, //详细信息子表有增行，其他没有
							showCheck: true,
							hideDel: !this.bodyActionFlag,
							hideModelSave: true,
							hideSwitch: () => {
								if (moduleId == AREA.cardTableId) {
									return true;
								}
								return false;
							},
							modelAddRow: () => {
								RownoUtils.setRowNo(this.props, AREA.cardTableId, FIELDS.crowno);
							},
							inputChange: inputChange.bind(this, FIELDS.crowno),
							selectedChange: onRowsSelected.bind(this),
							onBeforeEvent: bodyBeforeEvent.bind(this),
							onAfterEvent: bodyAfterEvent.bind(this),
							onBatchChange: batchEvents.bind(this)
						})}
					</NCScrollElement>
				);
			})}
            {/* 分摊明细-定义Dom */}
            {
                createCardTable('list_head', {
                    showCheck: false,
                    showIndex: false
                })
            }
		</div>
	);
}

// 公共组件
function billPublicArea(createModal, pk) {
	return (
		<div>
			<BillTrack
				show={this.state.showTrack}
				close={() => {
					this.setState({ showTrack: false });
				}}
				pk={this.state.pk}
				type="Z2"
			/>
			<ApproveDetail
				show={this.state.showApproveInfo}
				close={() => {
					this.setState({
						showApproveInfo: false
					});
				}}
				billtype={this.state.billtype}
				billid={this.state.pk}
			/>
			{this.state.showUploader && (
				<NCUploader
					billId={this.state.pk}
					target={this.state.target}
					onHide={() => {
						this.setState({
							showUploader: false
						});
					}}
					billcode={pk}
					pk_billtypecode={'Z2'}
				/>
			)}
			<ControlScopeDlg
				show={this.state.showControl}
				isBatch={this.state.isBatchControl}
				pk={this.state.pk}
				close={() => {
					this.setState({
						showControl: false
					});
				}}
			/>
			<DocManagement
				show={this.state.showDoc}
				billId={this.state.pk}
				billType="Z2"
				toggleShow={this.toggleDocShow}
				asyncTree={this.props.asyncTree}
			/>
			{this.state.showPane && (
				<MulTabPane
					show={this.state.showPane}
					pagecode={PAGECODE.histPagecode}
					title={getLangByResId(this, '4004PURDAILY-000047')} /* 国际化处理： 采购合同维护*/
					headcode={AREA.cardFormId}
					bodycode={[
						AREA.cardTableId,
						AREA.cardTermId,
						AREA.cardFeeId,
						AREA.cardMemoraId,
						AREA.cardChangeId,
						AREA.cardExecutId
					]}
					data={this.paneData}
					close={() => {
						this.setState({ showPane: false });
					}}
					showBodyData={true}
				/>
			)}
			{createModal('ResumeMessageDlg', {
				className: 'iframe-modal',
				size: 'xlg'
			})}
			{createModal('ScriptActionDlg')}
			{this.state.compositedisplay && (
				<ApprovalTrans
					title={getLangByResId(this, '4004PURDAILY-000049')} /* 国际化处理： 指派*/
					data={this.state.compositedata}
					display={this.state.compositedisplay}
					getResult={this.getResult.bind(this)}
					cancel={() => {
						this.setState({ compositedisplay: false, saveAndCommit: false });
					}}
				/>
			)}
		</div>
	);
}

function ref20Selected(status, index, record) {
	this.isEdit = false;
	this.props.beforeUpdatePage();
	this.props.form.setFormItemsDisabled(AREA.cardFormId, {
		[FIELDS.pk_org_v]: true
	});

	this.props.form.setAllFormValue({
		[AREA.cardFormId]: record.head[AREA.cardFormId]
	});
	CARDTABLEAREAIDS.forEach((areaId) => {
		if (record.bodys[areaId] && record.bodys[areaId].rows && record.bodys[areaId].rows.length > 0) {
			this.props.cardTable.setTableData(areaId, record.bodys[areaId], null, true, true);
		} else {
			this.props.cardTable.setTableData(areaId, { rows: [] }, null, true, true);
		}
	});
	//this.props.cardTable.setTableData(AREA.cardTableId, record.bodys[AREA.cardTableId], null, true, true);
	RownoUtils.setRowNo(this.props, AREA.cardTableId, FIELDS.crowno);
	buttonControl.call(this, this.props, status ? UISTATUS.browse : UISTATUS.edit);
	this.props.updatePage(AREA.cardFormId, CARDTABLEAREAIDS);
}

PurdailyCard = createPage({
	orderOfHotKey: [
		AREA.cardFormId,
		AREA.cardTableId,
		AREA.cardTermId,
		AREA.cardPayId,
		AREA.cardFeeId,
		AREA.cardMemoraId
	],
	billinfo: {
		billtype: 'extcard',
		pagecode: PAGECODE.cardPagecode,
		headcode: AREA.cardFormId,
		bodycode: {
			[AREA.cardTableId]: 'cardTable',
			[AREA.cardTermId]: 'cardTable',
			[AREA.cardPayId]: 'cardTable',
			[AREA.cardFeeId]: 'cardTable',
			[AREA.cardMemoraId]: 'cardTable',
			[AREA.cardChangeId]: 'cardTable',
			[AREA.cardExecutId]: 'cardTable'
		}
	}
})(PurdailyCard);

export default PurdailyCard;

/*2S7LXljdWdGhrCxZ1MFl4nbo76lbmNV/zj9vAsZ4TsJjt35I/W4VBwuu/33I9fcb*/
